import { Component, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CascaderItem, DValidateRules, FileUploader, FormLayout, IFileOptions, IUploadOptions, DialogService } from 'ng-devui';
import { DirctoryService } from 'src/app/@core/services/dirctory/dirctory.service';
import { MaterialService } from 'src/app/@core/services/material/material.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-edit-material',
  templateUrl: './edit-material.component.html',
  styleUrls: ['./edit-material.component.scss']
})
export class EditMaterialComponent {
  msg:any;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  options: any=[];
  Material = {
    partName:'',
    partNum:'',
    englishName:'',
    partType:'',
    mnemonicCode:'',
    partClassId:null,
    description:'',
    fileURL:'',
    costPrice:null,
    salePrice:null,
    partProperty:'',
    partUOM:'',
    minimumStock:null,
    maximumStock:null,
    safetyInventory:null,
    warehouseID:null,
    positionID:null,
    addFileURL:'',
    supplyId:null,
    supplyName:'',
    supplyNum:'',
    isInspection:false,
  }
  allUnits: any=[];
  currentNode: any;
  displayImg: any = [];
  option: Array<number> = [];//物料分类
  allWarehouses: Array<number>=[] //所有仓库
  allPositions: Array<number>=[] //所有库位
  message: Array<Object> = [];
  uploadedFiles: Array<Object> = [];
  fileUploaders: Array<FileUploader> = [];
  isDropOver = false;
  uploadOptions: IUploadOptions = {
    uri:environment.apiUrl+'/Part/UploadAvatar',
    maximumSize: 1024,
    checkSameName: true,
    fileFieldName:"file",
  };
  uploadOptions2: IUploadOptions = {
    uri: environment.apiUrl+'/Part/UploadAttachment',
    method: 'post',
    maximumSize: 20,
    checkSameName: true
  };
  fileOptions: IFileOptions = {
    multiple: true
  };
  fileOptions2: IFileOptions = {
    multiple: true,
    accept: '.xls,.xlsx,.pages,.mp3,.png',
  };
  materialHeaderUrls: string[] = [];
  disContainer: boolean = false;
  UPLOADED: string;
  CANCELUPLOAD: string;
  materialHeaderUrl: any;
  MaterialRules:{[key:string]:DValidateRules} = {
    partNum: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*物料编码不能为空' },
        { minlength: 2, message: '*物料编码长度至少为2' },
        { maxlength: 40, message: '*物料编码长度至多为40' },
      ],
    },
    partName: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*物料名称不能为空' },
        { maxlength: 40, message: '*物料名称长度至多为40' },
      ],
    },
    englishName: {
      messageShowType:'text',
      validators: [
        { maxlength: 40, message: '*英文名称长度至多为40' },
      ],
    },
    partType: {
      messageShowType:'text',
      validators: [
      ],
    },
    mnemonicCode: {
      messageShowType:'text',
      validators: [
        { maxlength: 40, message: '*助记码长度至多为40' },
      ],
    },
    partClassid: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*物料类别不能为空' },
      ],
    },
    wareName: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*仓库不能为空' },
      ],
    },
    positionName: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*库位不能为空' },
      ],
    },
    description: {
      messageShowType:'text',
      validators: [
        { maxlength: 200, message: '*物料描述长度至多为200' },
      ],
    },
    costPrice: {
      messageShowType:'text',
      validators: [
        { pattern: /^[1-9][0-9]*$/, message: '*成本价只能为数字' }
      ],
    },
    salePrice: {
      messageShowType:'text',
      validators: [
        { pattern: /^[1-9][0-9]*$/, message: '*销售价只能为数字' }
      ],
    },
    partProperty: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*物料属性不能为空' },
      ],
    },
    partUOM: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*物料单位不能为空' },
      ],
    },
    minimumStock: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*最小库存不能为空' },
        { pattern: /^[1-9][0-9]*$/, message: '*最小库存不能为负数' }
      ],
    },
    maximumStock: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*最大库存不能为空' },
        { pattern: /^[1-9][0-9]*$/, message: '*最大库存不能为负数' }
      ],
    },
    safetyInventory: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*安全库存不能为空' },
        { pattern: /^[1-9][0-9]*$/, message: '*安全库存不能为负数' }
      ],
    },
  }
  file: any;
  id: any;
  constructor(private MaterialService :MaterialService ,private StorehouseService:StorehouseService,private route:ActivatedRoute,private Router:Router,private DialogService:DialogService,private DirctoryService:DirctoryService){
  }
  ngOnInit(): void {
    this.route.params.subscribe(params => {
      const id = params['id'];
      this.id = id;
      const pathPids = params['pathPids'];
      this.MaterialService.getPartById(id).subscribe((res: any) => {
        this.Material = res;
        this.displayImg = this.Material.fileURL ? this.Material.fileURL.split(',') : []; // 将逗号隔开的字符串转换为数组
        this.fileUploaders = this.displayImg.map((url: string) => ({
          fileURL: url,
          status: 2, // 假设状态为 2 表示上传成功
          file: { name: this.getFileNameFromURL(url) } // 假设你有一个方法来从 URL 中提取文件名
        }));
        if (this.Material.warehouseID) {
          this.StorehouseService.getWarehousePositionsByWarehouseId(this.Material.warehouseID, 1, 999).subscribe((res: any) => {
            this.allPositions = res.items;
          });
        }
        this.MaterialService.getPartClassesWithChildren(1, 999).subscribe((res: any) => {
          this.options = this.convertToCascaderItem(res.items);
          for (let node of res.items) {
            const path = this.findClassByValue(node, this.Material.partClassId);
            if (path) {
              this.option = path;
              break;
            }
          }
        });
      });
    });
    this.StorehouseService.getWarehouses().subscribe((res: any) => {
      this.allWarehouses = res.items;
    });
    this.DirctoryService.getDictionaryEntriesByCategoryName("物料单位").subscribe((res: any) => {
      this.allUnits = res.value
    })
  }
  convertToCascaderItem(data: any[]): CascaderItem[] {
    return data.map(item => {
      let cascaderItem: CascaderItem = {
        label: item.partClassName,
        value: item.partClassId,
        pid: item.parentPartClassId,
      };
      if (item.subPartClasses) {
        cascaderItem.children = this.convertToCascaderItem(item.subPartClasses);
      }
      return cascaderItem;
    });
  }//转换数据格式为华为库练级菜单的数据格式
  CascaderonChanges($event:any){
    this.Material.partClassId = $event[$event.length-1]
  }
  wareHouseChanges($event:any){
    this.Material.warehouseID = $event.warehouseId
    if(this.Material.warehouseID){
      this.StorehouseService.getWarehousePositionsByWarehouseId(this.Material.warehouseID,1,999).subscribe((res:any)=>{
        this.allPositions = res.items
      })
    }
  }
  getFileNameFromURL(url: string): string {
    return url.substring(url.lastIndexOf('/') + 1);
  }
  PositionChanges($event:any){
    this.Material.positionID = $event.positionId
  }
  submit($event:any ){
    if ($event.valid) {
      this.MaterialService.UpdatePart(this.id,this.Material).subscribe((res:any)=>{
        this.showToast('success','成功','更新成功')
          setTimeout(() => {
            this.Router.navigate(['/pages/basicdata/material'])
          }, 1500);
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
      )
    }else{
      this.showToast('warning','失败','请按照要求填写表单')
    }
  }
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msg = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  cancle(){
    this.Router.navigate(['/pages/basicdata/material'])
  }
  onSuccess(event: any) {
    const response = event.map((item: { response: string; }) => JSON.parse(item.response).avatarUrl);
    this.materialHeaderUrls = response;
    const trimmedUrls = response.map((url: string) => url.replace(environment.modifiedApiUrl, ""));
    const resultString = trimmedUrls.join(',');
    // 在原有的基础上添加新的URL，用逗号隔开
    if (this.Material.fileURL) {
      this.Material.fileURL += ',' + resultString;
    } else {
      this.Material.fileURL = resultString;
    }
  } //上传成功
  onError(event: any) {
    this.disContainer =true;
  }
  deleteimg(index: any) {
    const urls = this.Material.fileURL.split(",");
    urls.splice(index, 1);
    this.Material.fileURL = urls.join(",");
  } //删除图片
  deleteFile(currFile: FileUploader) {
    this.fileUploaders = this.fileUploaders.filter((fileUploader) => {
      return currFile !== fileUploader;
    });
    const responseObj = this.fileUploaders.map(item => JSON.parse(item.response).avatarUrl);
    this.materialHeaderUrls = responseObj
    const trimmedUrls = responseObj.map((url: string) => url.replace(environment.modifiedApiUrl, ""));
    const resultString = trimmedUrls.join(',');
    this.Material.fileURL = resultString;
  }
  getImagesArray(fileURL: string): string[] {
    if (!fileURL) {
      return [];
    }
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  findClassByValue(node: any ,value:any,path=[]) {
    if(node.partClassId === value){
      return[...path,node.partClassId]
    }
    if(node.subPartClasses){
      for(let subNode of node.subPartClasses){
        const subPath = this.findClassByValue(subNode,value,[...path,node.partClassId])
        if(subPath){
          return subPath
        }
      }
    }
  }
  onButtonClick(dialogtype?:string) {
    const results = this.DialogService.open({
      title: '物料附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '物料附件',
        urls: this.Material.addFileURL
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.Material.addFileURL = results.modalContentInstance.urls;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectSupplier(dialogtype?:string){
    const results = this.DialogService.open({
      title: '选择供应商',
      width: '1200px',
      backdropCloseable: false,
      content: SelectSupplierComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              this.Material.supplyId = results.modalContentInstance.selectData.supplyId;
              this.Material.supplyName = results.modalContentInstance.selectData.supplyChineseName;
              this.Material.supplyNum = results.modalContentInstance.selectData.supplyNum;
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  gerFileNum(fileURL: string): number {
    if(fileURL === null || fileURL === '') {
      return 0;
    }
    return fileURL.split(',').length;
  }
}
